<template>
  <div>
    <form ref="form" method="post" enctype="multipart/form-data">
      <input :id="pickerId" type="button" @click="upload"/>
    </form>
    <label :for="pickerId">
      <slot name="picker">
        <em>upload</em>
      </slot>
    </label>
  </div>
</template>

<script>
  export default {
    props: {
      action: {
        type: String,
        default: 'https://upload.qiniu.com'
      },
      token: {
        type: String,
        default: ''
      },
      imgKey: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        pickerId: `picker${new Date().getTime()}`
      }
    },
    mounted () {
    },
    methods: {
      upload () {
        console.log('上传图片')
        this.$wx.chooseImage({
          count: 1, // 默认9
          // sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: res => {
            console.log(res)
            let localIds = res.localIds // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            console.log(localIds)
            this.$wx.getLocalImgData({
              localId: localIds[0], // 图片的localID
              success: function (res) {
                let localData = res.localData // localData是图片的base64数据，可以用img标签显示
                console.log(localData)
              }
            })
          }
        })
      },
      postImageToQiniu (base64Data) {
        let token = this.token
        let pic = base64Data.replace(/^.*?,/, '')
//        let url = 'http://upload.qiniu.com/putb64/' + fileSize; // 非华东空间需要根据注意事项 1 修改上传域名
        let url = this.action + '/putb64/-1' // 非华东空间需要根据注意事项 1 修改上传域名
        let xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
            let res = JSON.parse(xhr.responseText)
            this.$emit('upload', res.key)
          }
        }
        xhr.open('POST', url, true)
        xhr.setRequestHeader('Content-Type', 'application/octet-stream')
        xhr.setRequestHeader('Authorization', 'UpToken ' + token)
        xhr.send(pic)
      }
    },
    components: {}
  }
</script>

<style lang="scss" scoped>
  form {
    display: none;
  }
</style>
